package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import java.util.Objects;

import com.iwhalecloud.citybrain.flow.platform.manager.application.common.event.ProcessInstanceStartEvent;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.threadlocal.StartUserHolder;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.AbstractEntityEventHandler;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.SpringUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.UserRepository;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.common.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.common.api.delegate.event.FlowableEventType;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Component;

/**
 * Handler - 流程实例创建完成事件处理
 *
 * @author lilh
 * @date 2019-01-28 16:00
 */
@Component
public class ProcessInstanceCreatedHandler extends AbstractEntityEventHandler {

    @Override
    public FlowableEventType getEventType() {
        return FlowableEngineEventType.PROCESS_CREATED;
    }

    @Override
    protected void doHandle(FlowableEntityEventImpl event) {
        ExecutionEntityImpl executionEntity = (ExecutionEntityImpl) event.getEntity();
        insertProcessInstanceTrace(executionEntity, event);
        //System.out.println("流程实例创建完成，实例id为：" + event.getProcessInstanceId());
    }

    private void insertProcessInstanceTrace(ExecutionEntityImpl executionEntity, FlowableEntityEventImpl event) {
        ProcessDefinition processDefinition = SpringUtils.getBean(RepositoryService.class).createProcessDefinitionQuery().processDefinitionId(event.getProcessDefinitionId()).singleResult();
        String businessKey = executionEntity.getBusinessKey();
        ProcessInstanceStartEvent startEvent = new ProcessInstanceStartEvent().setProcessDefinition(processDefinition).setProcessInstance(executionEntity).setIsFromSdkCall(Objects.equals(businessKey, "isFromSdkCall"));
        if (!startEvent.getIsFromSdkCall()) {
            startEvent.setUser(SpringUtils.getBean(UserRepository.class).getCurrentUser());
        } else {
            startEvent.setUser(StartUserHolder.getUser());
        }
        SpringUtils.publishEvent(startEvent);
    }
}
